import auth from '@/apis/auth'
import router from '@/router'

const state = {
    user:null,
}
const getters = {
    username: state => state.user != null ? state.user.username : '未登录',
    slug: state=> state.user!=null ? state.user.username.charAt(0): '未'
}
const mutations = {
    setUser(state,payload) {
        state.user=payload.user
    }

}
const actions = {
    login({ commit }, { username, password }) {
        return auth.login({ username, password }).then((res) => {
             commit('setUser',{user:res.data})
         }).catch((res)=>{})
    },
    register({ commit }, { username, password }) {
        return auth.register({ username, password }).then((res) => {
            commit('setUser',{user:res.data})
        })
    },
    checkLogin({ commit }, payload) {
        return auth.getInfo().then((res) => {
            if (!res.isLogin) {
           
                if (payload) {
                    router.push(payload)    
                }
                
            } else {
                commit('setUser',{user:res.data})
            }
        })
    }
    
}
export default {
    state,
    getters,
    mutations,
    actions,
}
